'''
Created on Jul 21, 2013

@author: Cihat Basol
'''

import logging
import threading
from Queue import Queue, Empty

from dexen.node.worker.executor import TaskExecutor



class WorkerCore(threading.Thread):
    def __init__(self, worker_name, db_client, associated_job=None):
        super(WorkerCore, self).__init__()
        self.daemon = True
        self._lock = threading.RLock()
        self.pending_executions = Queue()
        self.execution_results = Queue()
        self.worker_name = worker_name
        self.db_client = db_client
        self.associated_job = associated_job
        self.logger = logging.getLogger(__name__+"."+self.__class__.__name__+
                                        "."+self.worker_name)

    def execute(self, execution):
        self.logger.debug("queuing execution for task: %s", execution.task.name)
        self.pending_executions.put(execution)
    
    def get_execution_result(self):
        try:
            result = self.execution_results.get_nowait()
        except Empty:
            self.logger.debug("execution result is not ready.")
            return None
        return result
    
    def run(self):
        while True:
            execution = self.pending_executions.get()
            task_executor = TaskExecutor(execution, self.execution_results, 
                                         self.worker_name, self.db_client)
            task_executor.execute()
            
